#include <QCoreApplication>
#include "RobotDef.h"
#include "tmrobotctrl.h"
#include "tmuserctrl.h"
#include "tmsessionmanager.h"
#include "tmglobaldef.h"

class Server : public Ice::Application
{
public:
    Server(QCoreApplication* p){
        m_pApp = p;
    }
    virtual int run(int argc, char* argv[]){
        // Init
        QString g_strRootDir = QCoreApplication::applicationDirPath();
        QDir::setCurrent(g_strRootDir);
        // 更新了全局RobotType和Version
//        QSettings g_pSettingCore = new QSettings("./Config/Robot.ini", QSettings::IniFormat);
//        g_pSettingCore->setIniCodec("UTF-8");
//        g_pCodecASCII = QTextCodec::codecForName("GB18030");
//        g_strRobotType = g_pSettingCore->value("Core/Type").toString();
//        g_strCoreVersion = g_pSettingCore->value("Core/Version").toString();

//        g_bAsrCmdMode = false;
        robotMap.clear();
        m_replyMsgMap.clear();

        g_pLog = new TmLog();

        pMySqlCtrl = new TMMySQLCtrl;
        if(pMySqlCtrl->connect_mysql("127.0.0.1")){
            g_pLog->log_D("connect mysql success!");
            qDebug()<<"connect mysql success!";
        }

        Ice::PropertiesPtr proptr = communicator()->getProperties();
        qDebug()<<"----Ice.MessageSizeMax:----"<<proptr->getProperty("Ice.MessageSizeMax").c_str();
        // Ice object
        Ice::ObjectAdapterPtr adapter = communicator()->createObjectAdapter("NetWorkRobot");
        // User
        TMUserCtrl* pUserCtrlI = new TMUserCtrl;
        adapter->add(pUserCtrlI, communicator()->stringToIdentity("UserManger"));

        adapter->activate();

        //callback
        Ice::ObjectAdapterPtr adapterCallBack = communicator()->createObjectAdapter("Callback.Server");
        TMRobotCallBackCtrl* pRobotCallBackCtrlI = new TMRobotCallBackCtrl();
        adapterCallBack->add(pRobotCallBackCtrlI, communicator()->stringToIdentity("RegCallBack"));
        adapterCallBack->activate();

        // SessionManager       
        Ice::ObjectAdapterPtr m_adapter_sm = communicator()->createObjectAdapter("SessionManagerAD");
        DummyPermissionsVerifierI *dpv = new DummyPermissionsVerifierI;
        m_adapter_sm->add(dpv, communicator()->stringToIdentity("SessionVerifier"));
        ClientSessionManagerI* csm = new ClientSessionManagerI;
        m_adapter_sm->add(csm, communicator()->stringToIdentity("SessionManager"));
        m_adapter_sm->activate();

        communicator()->waitForShutdown();

        QCoreApplication::processEvents();
//        m_pApp->quit();
        m_pApp->exit();
        return 0;
    }
private:
    QCoreApplication* m_pApp;

};

void t_run(QCoreApplication* p){
    Server app(p);
    app.main(__argc, __argv);
}

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    std::thread t1(t_run, &a);
    t1.detach();
    return a.exec();
}
